package com.xuecheng.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.CommonError;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.config.MultipartSupportConfig;
import com.xuecheng.content.feignclient.MediaServiceClient;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CoursePublishMapper;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.CoursePreviewDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.model.po.CoursePublishPre;
import com.xuecheng.content.service.*;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CoursePublishServiceImpl extends ServiceImpl<CoursePublishMapper, CoursePublish> implements CoursePublishService {

    @Autowired
    private CourseBaseService courseBaseService;
    @Autowired
    private TeachplanService teachplanService;
    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private CourseMarketService courseMarketService;
    @Autowired
    private CoursePublishPreService coursePublishPreService;
    @Autowired
    private CoursePublishMapper coursePublishMapper;
    @Autowired
    private MqMessageService mqMessageService;
    @Autowired
    private MediaServiceClient mediaServiceClient;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据课程id查询相关消息
     *
     * @param courseId
     * @return
     */
    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
        //1.获取课程基本消息和营销消息
        CourseBaseInfoDto courseBaseInfoDto = courseBaseService.getcourseBaseInfo(courseId);

        //2.获取课程计划消息
        List<TeachplanDto> teachPlanTree = teachplanService.findTeachPlanTree(courseId);

        //3.合并
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        coursePreviewDto.setCourseBase(courseBaseInfoDto);
        coursePreviewDto.setTeachplans(teachPlanTree);

        return coursePreviewDto;

    }

    @Override
    @Transactional
    public void commitAudit(Long companyId, Long courseId) {

        //1.校验
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        //本机构只允许提交本机构的课程
        if (!companyId.equals(courseBase.getCompanyId())) {
            XueChengPlusException.cast("不允许提交其他机构的课程");
        }
        //课程审核状态
        String auditStatus = courseBase.getAuditStatus();
        if ("202003".equals(auditStatus)) {
            XueChengPlusException.cast("当前为等待审核状态，审核完成可以再次提交。");
        }
        //课程图片是否填写
        if (StringUtils.isEmpty(courseBase.getPic())) {
            XueChengPlusException.cast("课程没有图片，无法提交");
        }

        //2.添加课程预记录表
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        //课程基本信息和部分营销信息
        CourseBaseInfoDto courseBaseInfoDto = courseBaseService.getcourseBaseInfo(courseId);
        //保存到课程预记录
        BeanUtils.copyProperties(courseBaseInfoDto, coursePublishPre);
        //课程营销信息
        CourseMarket courseMarket = courseMarketService.getById(courseId);
        //转换为json格式
        String courseMarketJson = JSON.toJSONString(courseMarket);
        coursePublishPre.setMarket(courseMarketJson);
        //课程计划
        List<TeachplanDto> teachPlanTree = teachplanService.findTeachPlanTree(courseId);
        if (teachPlanTree.size() <= 0) {
            XueChengPlusException.cast("提交失败");
        }
        //转换为json格式
        String teachPlanTreeJson = JSON.toJSONString(teachPlanTree);
        coursePublishPre.setTeachplan(teachPlanTreeJson);

        //设置预发布记录状态,已提交
        coursePublishPre.setStatus("202003");
        //教学机构id
        coursePublishPre.setCompanyId(companyId);
        //提交时间
        coursePublishPre.setCreateDate(LocalDateTime.now());

        //3.向预发表表中添加信息
        CoursePublishPre publishPre = coursePublishPreService.getById(courseId);
        if (publishPre == null) {
            //添加课程预发布记录
            coursePublishPreService.save(coursePublishPre);
        } else {
            coursePublishPreService.updateById(coursePublishPre);
        }

        //更新课程信息表审核状态
        courseBase.setAuditStatus("202003");
        courseBaseMapper.updateById(courseBase);
    }


    /**
     * 课程发布
     *
     * @param companyId
     * @param courseId
     */
    @Override
    @Transactional
    public void publish(Long companyId, Long courseId) {

        //1.校验
        CoursePublishPre publishPre = coursePublishPreService.getById(courseId);
        if (publishPre == null) {
            XueChengPlusException.cast("请先提交课程审核，审核通过才能提交");
        }
        if (!companyId.equals(publishPre.getCompanyId())) {
            XueChengPlusException.cast("只运行提交本机构的课程");
        }
        //课程审核状态
        String auditStatus = publishPre.getStatus();
        //审核通过方可发布
        if (!"202004".equals(auditStatus)) {
            XueChengPlusException.cast("操作失败，课程审核通过方可发布。");
        }

        //2.保存课程发布信息
        saveCoursePublish(courseId);

        //3.保存信息表
        saveCoursePublishMessage(courseId);

        //4.删除预课程发布表中的信息
        coursePublishPreService.removeById(courseId);

    }


    /**
     * 保存信息表
     *
     * @param courseId
     */
    private void saveCoursePublishMessage(Long courseId) {
        MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
        if (mqMessage == null) {
            XueChengPlusException.cast(CommonError.UNKOWN_ERROR);
        }
    }


    /**
     * 保存课程信息表
     *
     * @param courseId
     */
    private void saveCoursePublish(Long courseId) {

        CoursePublishPre publishPre = coursePublishPreService.getById(courseId);
        //1.校验
        if (publishPre == null) {
            XueChengPlusException.cast("课程预发布数据为空");
        }
        //2.向课程发布表中插入一条记录
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(publishPre, coursePublish);
        coursePublish.setStatus("203002");
        CoursePublish coursePublish1 = coursePublishMapper.selectById(courseId);
        if (coursePublish1 == null) {
            //插入
            coursePublishMapper.insert(coursePublish);
        } else {
            //更新
            coursePublishMapper.updateById(coursePublish);
        }

        //3.更新课程基本信息表
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        courseBase.setStatus("203002");
        courseBaseMapper.updateById(courseBase);
    }

    /**
     * 课程静态化
     *
     * @param courseId
     * @return
     */
    @Override
    public File generateCourseHtml(Long courseId) {
        //静态化文件
        File htmlFile = null;
        try {
            //获取参数1
            //配置freemarker
            Configuration configuration = new Configuration(Configuration.getVersion());
            //加载模板
            //选指定模板路径,classpath下templates下
            //得到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //编码
            configuration.setDefaultEncoding("utf-8");
            Template template = configuration.getTemplate("course_template.ftl");


            //获取参数2
            //准备数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);
            HashMap<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);
            //静态化
            //参数1：模板，参数2：数据模型
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);

            //转换成文件
            //将静态化内容输出到文件中
            InputStream inputStream = IOUtils.toInputStream(content);
            //创建静态化文件
            htmlFile = File.createTempFile("course", ".html");
            log.debug("课程静态化，生成静态文件:{}", htmlFile.getAbsolutePath());
            //输出流
            FileOutputStream fileOutputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, fileOutputStream);

        } catch (Exception e) {
            log.error("课程静态化异常:{}", e.toString());
            XueChengPlusException.cast("课程静态化异常");
        }
        return htmlFile;
    }

    /**
     * 上传静态化页面
     *
     * @param courseId
     * @param file
     */
    @Override
    public void uploadCourseHtml(Long courseId, File file) {

        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);

        String course = mediaServiceClient.upload(multipartFile, "course/" + courseId + ".html");
        if (course == null) {
            XueChengPlusException.cast("上传静态文件异常");
        }
    }


    /**
     * 查询课程发布信息
     *
     * @param courseId
     * @return
     */
    @Override
    public CoursePublish getCoursePublish(Long courseId) {
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        return coursePublish;
    }


    /**
     * 实现查询缓存
     *
     * @param courseId
     * @return
     */
    @Override
    public CoursePublish getCoursePublishCache(Long courseId) {
        //查询缓存
        Object jsonObj = redisTemplate.opsForValue().get("course:" + courseId);
        if (jsonObj != null) {
            String string = jsonObj.toString();
            System.out.println("-----------------从缓存中查---------------");
            CoursePublish coursePublish = JSON.parseObject(string, CoursePublish.class);
            return coursePublish;
        } else {
            System.out.println("-------------从数据库中查-------------");
            //从数据库中查
            CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
            if (coursePublish != null) {
                redisTemplate.opsForValue().set("course" + courseId, JSON.toJSONString(coursePublish));
            }
            return coursePublish;
        }
    }
}
